/**
 * @fileoverview
 * This script defines a widget for finding a batch of D. mel genes via Flybase.
 * @version $Revision:539 $ on $Date: 2008-08-13 16:09:30 +0100 (Wed, 13 Aug 2008) $ by $Author: aliman $
 * @requires YAHOO.log
 * @requires YAHOO.lang.JSON
 * @requires YAHOO.util.Dom
 * @requires YAHOO.util.Connect
 * @requires YAHOO.util.CustomEvent
 * @requires flyui.util
 * @requires flyui.flybase
 * TODO license terms
 */
 
flyui.namespace("flyui.genefinder");




/*
 * ----------------------------------------------------------------
 *                             WIDGET
 * ----------------------------------------------------------------
 */





/**
 * @class
 */
flyui.genefinder.BatchWidget = function( service, renderer ) {
    var _context = "flyui.genefinder.BatchWidget";
    try {
        
        flyui.debug("call private constructor", _context);
        this.__init__(service, renderer);
        
    } catch (unexpected) {
        flyui.debug("rethrowing "+unexpected.name+", "+unexpected.message, _context);
        throw unexpected;    
    }
};





/** @private */
flyui.genefinder.BatchWidget.prototype._controller = null;

/**
 * @private
 * @type flyui.mvcutils.GenericModel2
 */ 
flyui.genefinder.BatchWidget.prototype._model = null;

/**
 * @private
 */
flyui.genefinder.BatchWidget.prototype._renderer = null;

/**
 * @private
 */
flyui.genefinder.BatchWidget.prototype._service = null;

/**
 * @private
 */
flyui.genefinder.BatchWidget.prototype._genesFoundEvent = null;





/**
 * @private
 */
flyui.genefinder.BatchWidget.prototype.__init__ = function( service, renderer ) {
    var _context = "flyui.genefinder.BatchWidget.prototype.__init__";
    try {
        
        this._service = service;
        this._renderer = renderer;
        
        flyui.debug("create events", _context);
        this._genesFoundEvent = new YAHOO.util.CustomEvent("GENESFOUND", this);
        
        flyui.debug("create a model", _context);
        this._model = new flyui.mvcutils.GenericModel2();
        this._model.setDefinition(flyui.genefinder.BatchWidget.modelDefinition);
        
        flyui.debug("create a controller", _context);
        this._controller = new flyui.genefinder.BatchWidget.Controller(this._model, service, this);
        
        flyui.debug("connect the renderer to the model", _context);
        this._renderer.connect(this._model);
        
    } catch (unexpected) {
        flyui.debug("rethrowing "+unexpected.name+", "+unexpected.message, _context);
        throw unexpected;    
    }
};





/**
 * @public
 */
flyui.genefinder.BatchWidget.prototype.subscribe = function( type, listener, obj ) {
    var _context = "flyui.genefinder.BatchWidget.prototype.subscribe";
    try {
        
        if (type == "GENESFOUND") {
            this._genesFoundEvent.subscribe(listener, obj);
        }
        
    } catch (unexpected) {
        flyui.debug("rethrowing "+unexpected.name+", "+unexpected.message, _context);
        throw unexpected;    
    }
    
};





/**
 * @public
 * @param {Array<String>} names
 */
flyui.genefinder.BatchWidget.prototype.findGenesByAnyNameBatch = function( names ) {
    var _context = "flyui.genefinder.BatchWidget.prototype.findGenesByAnyNameBatch";
    try {
        
        flyui.debug("pass ["+names+"] through to controller", _context);
        this._controller.findGenesByAnyNameBatch(names);
        
    } catch (unexpected) {
        flyui.debug("rethrowing "+unexpected.name+", "+unexpected.message, _context);
        throw unexpected;    
    }
};





/*
 * ----------------------------------------------------------------
 *                             CONTROLLER
 * ----------------------------------------------------------------
 */





/**
 * @class
 */
flyui.genefinder.BatchWidget.Controller = function( model, service, controllee ) {
    var _context = "flyui.genefinder.BatchWidget.Controller";
    try {
        
        this._model = null;
        this._service = null;
        this._controllee = null;
        
        flyui.debug("call private constructor", _context);
        this.__init__(model, service, controllee);        
        
    } catch (unexpected) {
        flyui.debug("rethrowing "+unexpected.name+", "+unexpected.message, _context);
        throw unexpected;    
    }
};





/**
 * @private
 */
flyui.genefinder.BatchWidget.Controller.prototype.__init__ = function( model, service, controllee ) {
    var _context = "flyui.genefinder.BatchWidget.Controller.prototype.__init__";
    try {
        
        this._model = model;
        this._service = service;
        this._controllee = controllee;
        
    } catch (unexpected) {
        flyui.debug("rethrowing "+unexpected.name+", "+unexpected.message, _context);
        throw unexpected;    
    }
};





/**
 * @public
 */
flyui.genefinder.BatchWidget.Controller.prototype.findGenesByAnyNameBatch = function( names ) {
    var _context = "flyui.genefinder.BatchWidget.Controller.prototype.findGenesByAnyNameBatch";
    try {
        
        flyui.info("findGenesByAnyNameBatch: "+names, _context);
        flyui.debug("pass through to private implementation", _context);
        this._findGenesByAnyNameBatch(names, this._findGenesByAnyNameBatchSuccess(), this._findGenesByAnyNameBatchFailure());
        
    } catch (unexpected) {
        flyui.debug("rethrowing "+unexpected.name+", "+unexpected.message, _context);
        throw unexpected;    
    }
};





/**
 * @private
 */
flyui.genefinder.BatchWidget.Controller.prototype._findGenesByAnyNameBatch = function( names, success, failure ) {
    var _context = "flyui.genefinder.BatchWidget.Controller.prototype._findGenesByAnyNameBatch";
    try {
        
        flyui.debug("names: "+names, _context);
        
        flyui.debug("set state pending", _context);
        this._model.set("STATE", "PENDING");
        
        flyui.debug("set model property query", _context);
        this._model.set("QUERY", names);

        flyui.debug("set result null", _context);
        this._model.set("RESULTS", null);
                
        flyui.debug("set message null", _context);
        this._model.set("MESSAGE", null);
                
        flyui.debug("kick off request", _context);
        this._service.findGenesByAnyNameBatch(names, success, failure);        
        
    } catch (unexpected) {
        flyui.debug("rethrowing "+unexpected.name+", "+unexpected.message, _context);
        throw unexpected;    
    }
};





/**
 * @private
 */
flyui.genefinder.BatchWidget.Controller.prototype._findGenesByAnyNameBatchSuccess = function() {
    var _context = "flyui.genefinder.BatchWidget.Controller.prototype._findGenesByAnyNameBatchSuccess";
    var self = this;
    /**
     * @param {Object<String,<Array<Gene>>} results a map from names in the query to arrays of gene objects
     */
    return function( results ) {
        try {
            
            flyui.info("request success", _context);
            
            flyui.debug("set model results", _context);
            self._model.set("RESULTS", results);
            
            flyui.debug("set model state", _context);
            self._model.set("STATE", "READY");
            
            flyui.debug("fire event", _context);
            self._controllee._genesFoundEvent.fire(self._model.get("QUERY"), results);
            
        } catch (unexpected) {
            flyui.debug("rethrowing "+unexpected.name+", "+unexpected.message, _context);
            throw unexpected;    
        }
    };
};





/**
 * @private
 */
flyui.genefinder.BatchWidget.Controller.prototype._findGenesByAnyNameBatchFailure = function() {
    var _context = "flyui.genefinder.BatchWidget.Controller.prototype._findGenesByAnyNameBatchFailure";
    var self = this;
    /**
     * @param {ResponseObject} response
     */
    return function( response ) {
        try {
            
            flyui.err("request failed: "+response.status+" "+response.statusText, _context);
            self._model.set("MESSAGE", "there was an error retrieving data from the server, see the logs for more info");
            self._model.set("STATE", "SERVERERROR");
            
        } catch (unexpected) {
            flyui.debug("rethrowing "+unexpected.name+", "+unexpected.message, _context);
            throw unexpected;    
        }
    };
};





/*
 * ----------------------------------------------------------------
 *                             MODEL DEFINITION
 * ----------------------------------------------------------------
 */





/** 
 * @type Object
 */
flyui.genefinder.BatchWidget.modelDefinition = {

    properties : [ "STATE", "RESULTS", "MESSAGE", "QUERY" ],
    
    values : {
        "STATE" : [ "READY", "PENDING", "SERVERERROR", "UNEXPECTEDERROR" ]
    },
    
    initialize : function( data ) {
        data["STATE"] = "READY";
        data["RESULTS"] = null;
        data["MESSAGE"] = null;
        data["QUERY"] = null;
    }

};





/*
 * ----------------------------------------------------------------
 *                             DEFAULT RENDERER
 * ----------------------------------------------------------------
 */


flyui.genefinder.BatchWidget.DefaultRenderer = function() {};


/** 
 * @private 
 * @type Element
 */
flyui.genefinder.BatchWidget.DefaultRenderer.prototype._canvas = null;

/**
 * @private 
 * @type Element
 */
flyui.genefinder.BatchWidget.DefaultRenderer.prototype._pendingPane = null;

/**
 * @private 
 * @type Element
 */
flyui.genefinder.BatchWidget.DefaultRenderer.prototype._resultsSummaryPane = null;

/**
 * @private 
 * @type Element
 */
flyui.genefinder.BatchWidget.DefaultRenderer.prototype._resultsPane = null;

/**
 * @private 
 * @type Element
 */
flyui.genefinder.BatchWidget.DefaultRenderer.prototype._messagePane = null;





/**
 * Set the DOM element to which this renderer applies and initialise it.
 * @param {Element} canvas
 */
flyui.genefinder.BatchWidget.DefaultRenderer.prototype.setCanvas = function( canvas ) {
    var _context = "flyui.genefinder.BatchWidget.DefaultRenderer.prototype.setCanvas";
    try {
        
        flyui.debug("set canvas", _context);
        this._canvas = $(canvas);
        this._initCanvas();
        
        
    } catch (unexpected) {
        flyui.debug("rethrowing "+unexpected.name+", "+unexpected.message, _context);
        throw unexpected;    
    }
};






/**
 * @private
 * @param {Element} canvas
 */
flyui.genefinder.BatchWidget.DefaultRenderer.prototype._initCanvas = function() {
    var _context = "flyui.genefinder.BatchWidget.DefaultRenderer.prototype._initCanvas";
    try {
        
        flyui.debug("begin init canvas", _context);
        
        var canvas = this._canvas;
        canvas.addClass("batchGeneFinderWidget");

        var pp = $("<p class='pendingPane'>pending...</p>").hide();
        canvas.append(pp);
        this._pendingPane = pp;

        var rsp = $("<p class='resultsSummaryPane'>this text should never be displayed</p>").hide();
        canvas.append(rsp);
        this._resultsSummaryPane = rsp;
        
        var rp = $("<div class='resultsPane'></div>").hide();
        canvas.append(rp);
        this._resultsPane = rp;
        
        var mp = $("<p class='messagePane'>this text should never be displayed</p>").hide();
        canvas.append(mp);
        this._messagePane = mp;            

        flyui.debug("init canvas done", _context);
        
    } catch (unexpected) {
        flyui.debug("rethrowing "+unexpected.name+", "+unexpected.message, _context);
        throw unexpected;    
    }
};





/**
 * @public
 */
flyui.genefinder.BatchWidget.DefaultRenderer.prototype.connect = function( model ) {
    var _context = "flyui.genefinder.BatchWidget.DefaultRenderer.prototype.connect";
    try {
        
        flyui.debug("connect to model", _context);
        model.subscribeAll(this._onModelChanged, this);
        
    } catch (unexpected) {
        flyui.debug("rethrowing "+unexpected.name+", "+unexpected.message, _context);
        throw unexpected;    
    }
};





/**
 * @private
 */
flyui.genefinder.BatchWidget.DefaultRenderer.prototype._onModelChanged = function( type, args, self ) {
    var _context = "flyui.genefinder.BatchWidget.DefaultRenderer.prototype._onModelChanged";
    try {
        
        var handlers = {
            "STATE":"_onStateChanged",
            "QUERY":"_onQueryChanged",
            "RESULTS":"_onResultsChanged",
            "MESSAGE":"_onMessageChanged", 
            "MODE":"_onModeChanged"
        };
        var handler = handlers[type];
        flyui.debug("call model changed handler: "+handler, _context);
        self[handler](args[0], args[1], args[2]);
        
    } catch (unexpected) {
        flyui.debug("rethrowing "+unexpected.name+", "+unexpected.message, _context);
        throw unexpected;    
    }
};






/**
 * @private
 */
flyui.genefinder.BatchWidget.DefaultRenderer.prototype._onQueryChanged = function( from, to, get ) {
    var _context = "flyui.genefinder.BatchWidget.DefaultRenderer.prototype._onQueryChanged";
    try {
        
        // do nothing, we will access the value later
        flyui.debug("query changed from "+from+" to "+to, _context);
        
    } catch (unexpected) {
        flyui.debug("rethrowing "+unexpected.name+", "+unexpected.message, _context);
        throw unexpected;    
    }
};






/**
 * @private
 */
flyui.genefinder.BatchWidget.DefaultRenderer.prototype._onStateChanged = function( from, to, get ) {
    var _context = "flyui.genefinder.BatchWidget.DefaultRenderer.prototype._onStateChanged";
    try {
        
        flyui.debug("state changed from "+from+" to "+to, _context);

        if ( to == "PENDING" ) {
            this._pendingPane.show();
            this._messagePane.hide();
            this._resultsSummaryPane.hide();
            this._resultsPane.hide();
        }
        else if ( to == "READY" ) {
            this._pendingPane.hide();
            this._messagePane.hide(); // hide for now, not needed yet
            this._resultsSummaryPane.show();
            this._resultsPane.show();         
        } 
        else if ( to == "SERVERERROR" || to == "UNEXPECTEDERROR" ) {
            this._pendingPane.hide();
            this._messagePane.show();
            this._resultsSummaryPane.hide();
            this._resultsPane.hide();         
        } 
        else {
            // this should never happen
            throw {message:"invalid state: "+to};
        }
        
    } catch (unexpected) {
        flyui.debug("rethrowing "+unexpected.name+", "+unexpected.message, _context);
        throw unexpected;    
    }
};






/**
 * @private
 */
flyui.genefinder.BatchWidget.DefaultRenderer.prototype._onResultsChanged = function( from, to, get ) {
    var _context = "flyui.genefinder.BatchWidget.DefaultRenderer.prototype._onResultsChanged";
    try {
        
        flyui.debug("results changed to: "+to, _context);
        
        if (to == null) {
            flyui.debug("empty results summary pane", _context);
            this._resultsSummaryPane.empty();
            flyui.debug("empty results pane", _context);
            this._resultsPane.empty();
        } 
        
        else {

            flyui.debug("render results summary", _context);
            this._renderResultsSummary(to);
    
            flyui.debug("render results", _context);
            this._renderResults(to);        
            
        }
        
    } catch (unexpected) {
        flyui.debug("rethrowing "+unexpected.name+", "+unexpected.message, _context);
        throw unexpected;    
    }
};







/**
 * @private
 */
flyui.genefinder.BatchWidget.DefaultRenderer.prototype._onMessageChanged = function( from, to, get ) {
    var _context = "flyui.genefinder.BatchWidget.DefaultRenderer.prototype._onMessageChanged";
    try {
        
        flyui.debug("message changed to: "+to, _context);
        
        if (to == null) {
            flyui.debug("empty messsage pane", _context);
            this._messagePane.empty();
        } 
        
        else {

            this._messagePane.html(to);
            
        }
        
    } catch (unexpected) {
        flyui.debug("rethrowing "+unexpected.name+", "+unexpected.message, _context);
        throw unexpected;    
    }
};







/**
 * @private
 * @param {Object<String,<Array<Gene>>} results a map from names in the query to arrays of gene objects
 */
flyui.genefinder.BatchWidget.DefaultRenderer.prototype._renderResultsSummary = function( results ) {
    var _context = "flyui.genefinder.BatchWidget.DefaultRenderer.prototype._renderResultsSummary";
    try {
        
        flyui.debug("render results summary", _context);
        var ok = 0;
        var notfound = 0;
        var ambiguous = 0;
        
        for (var key in results) {
            flyui.debug("inspecting key: "+key, _context);
            var genes = results[key];
            if (genes.length == 0) {
                notfound++;
            }
            else if (genes.length == 1) {
                ok++;
            }
            else {
                ambiguous++;
            }
        }
        
        var content = "found "+ok+" OK, "+ambiguous+" ambiguous, "+notfound+" not found from <a href='http://flybase.org'>flybase.org</a> (FB2009_02) ...";
        this._resultsSummaryPane.html(content);
        
    } catch (unexpected) {
        flyui.debug("rethrowing "+unexpected.name+", "+unexpected.message, _context);
        throw unexpected;    
    }
};








/**
 * @private
 * @param {Object<String,<Array<Gene>>} results a map from names in the query to arrays of gene objects
 */
flyui.genefinder.BatchWidget.DefaultRenderer.prototype._renderResults = function( results ) {
    var _context = "flyui.genefinder.BatchWidget.DefaultRenderer.prototype._renderResults";
    try {
        
        var renderFlybaseLink = function(gene) {
            return "<a href='http://flybase.org/reports/"+gene.flybaseID+".html'>"+gene.flybaseID+"</a>";
        }
        
        flyui.debug("render results", _context);
        var found = "<strong>found:</strong> ";
        var notfound = "<strong>not found:</strong> ";
        var ambiguous = "<strong>ambiguous:</strong> ";
        
        var foundcount = 0;
        var notfoundcount = 0;
        var ambiguouscount = 0;
        
        for (var key in results) {
            flyui.debug("inspecting key: "+key, _context);
            var genes = results[key];
            if (genes.length == 0) {
                notfoundcount++;
                notfound += key + "; ";
            }
            else if (genes.length == 1) {
                foundcount++;
                found += key + " (" + renderFlybaseLink(genes[0]) + "); ";
            }
            else {
                ambiguouscount++;
                ambiguous += key +" (";
                for (var i=0; i<genes.length; i++) {
                    ambiguous += renderFlybaseLink(genes[i]);
                    if (i<genes.length-1) {
                        ambiguous += ", ";
                    }
                }
                ambiguous += "); ";
            }
        }
        
        var content = "";
        if (foundcount > 0) content += "<p>"+found+"</p>";
        if (ambiguouscount > 0) content += "<p>"+ambiguous+"</p>";
        if (notfoundcount > 0) content += "<p>"+notfound+"</p>";
        this._resultsPane.html(content);
        
    } catch (unexpected) {
        flyui.debug("rethrowing "+unexpected.name+", "+unexpected.message, _context);
        throw unexpected;    
    }
};








